package com.cash.loan.core.upload;

import com.cash.loan.config.properties.QiniuProperties;
import com.cash.loan.core.common.exception.BizExceptionEnum;
import com.cash.loan.core.exception.GunsException;
import com.cash.loan.core.util.DateUtil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

/**
 * @author Administrator
 * @decription
 * @Date 2017-12-20 17:00
 */
@Component
public class QiniuService {

    private static final String CHINA_EAST = "华东";

    private static final String CHINA_NORTH = "华北";

    private static final String CHINA_SOUTH = "华南";

    private static final String NORTH_AMERICA = "北美";

    @Autowired
    private QiniuProperties properties;

    public String uploadFile(String localFile) throws QiniuException {
        File file = new File(localFile);
        String fileType = localFile.substring(localFile.lastIndexOf(".") + 1,localFile.length());
        return uploadFile(file,fileType);
    }

    public String uploadFile(File file, String fileType) throws QiniuException {
        String date = DateUtil.format(new Date(),"yyyyMMdd");
        String fileName = date + "/" + UUID.randomUUID() + "." + fileType;
        String upToken = getUpToken();
        UploadManager uploadManager = getUploadManager();
        Response response = uploadManager.put(file,fileName,upToken);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return properties.getDomain() + "/" + putRet.key;
    }

    public String upload(String key, String content) throws QiniuException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes());
        String upToken = getUpToken();
        UploadManager uploadManager = getUploadManager();
        Response response = uploadManager.put(inputStream,key,upToken,null,null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return properties.getDomain() + "/" + putRet.key;
    }

    public String upload(String fileType, InputStream content) throws QiniuException {
        String date = DateUtil.format(new Date(),"yyyyMMdd");
        String fileName = date + "/" + UUID.randomUUID()  + fileType;
        String upToken = getUpToken();
        UploadManager uploadManager = getUploadManager();
        Response response = uploadManager.put(content,fileName,upToken,null,null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return properties.getDomain() + "/" + putRet.key;
    }

    public String upload(String name, String fileType, InputStream content) throws QiniuException {
        String date = DateUtil.format(new Date(),"yyyyMMdd");
        String fileName = date + "/" + name  + fileType;
        String upToken = getUpToken();
        UploadManager uploadManager = getUploadManager();
        Response response = uploadManager.put(content,fileName,upToken,null,null);
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        return properties.getDomain() + "/" + putRet.key;
    }

    public String getUrl(String uri) {
        return properties.getDomain() + uri;
    }

    public String getUri(String url) {
        return url.substring(properties.getDomain().length(),url.length());
    }

    public String getDownloadFileUrl(String filename) throws Exception {
        String encodedFileName = URLEncoder.encode(filename, "utf-8");
        String finalUrl = String.format("%s/%s", properties.getDomain(), encodedFileName);
        return finalUrl;
    }

    public String getPrivateDownloadFileUrl(String filename) throws Exception {
        Auth auth = getAuth();
        long expireTime = Long.valueOf(properties.getExpireTime());
        String encodedFileName = URLEncoder.encode(filename, "utf-8");
        String finalUrl = auth.privateDownloadUrl(encodedFileName,expireTime);
        return finalUrl;
    }

    public void deleteFile(String filename) throws QiniuException {
        BucketManager bucketManager = getBucketManager();
        bucketManager.delete(properties.getBucketName(),filename);
    }

    public String getUpToken() {
        Auth auth = getAuth();
        String upToken = auth.uploadToken(properties.getBucketName());
        return upToken;
    }

    private Auth getAuth() {
        Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
        return auth;
    }

    /**
     * 得到上传管理器
     * @return
     */
    private UploadManager getUploadManager() {
        Zone zone = getZone();
        Configuration configuration = new Configuration(zone);
        UploadManager uploadManager = new UploadManager(configuration);
        return uploadManager;
    }

    private BucketManager getBucketManager() {
        Zone zone = getZone();
        Auth auth = getAuth();
        Configuration configuration = new Configuration(zone);
        BucketManager bucketManager = new BucketManager(auth, configuration);
        return bucketManager;
    }

    private Zone getZone() {
        Zone zone = null;
        if(CHINA_EAST.equals(properties.getZone())) {
            zone = Zone.zone0();
        } else if(CHINA_NORTH.equals( properties.getZone() )) {
            zone = Zone.zone1();
        } else if(CHINA_SOUTH.equals( properties.getZone() )) {
            zone = Zone.zone2();
        } else if(NORTH_AMERICA.equals( properties.getZone() )){
            zone = Zone.zoneNa0();
        } else {
            throw new GunsException(BizExceptionEnum.QINIU_NOT_ZONE);
        }
        return zone;
    }
}
